package com.antis.olsl.magic.profit.cost;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.antis.olsl.base.BaseFragment;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomView;
import com.antis.olsl.magic.adapter.MagicIndicatorAdapter;
import com.antis.olsl.magic.databinding.FragmentCostAnalysisBinding;
import com.trello.rxlifecycle2.LifecycleTransformer;

import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

/**
 * 成本分析
 *
 * @author hhh
 */
public class CostAnalysisFragment extends BaseFragment<FragmentCostAnalysisBinding> implements ChooseSalesroomView.ChooseSalesroomListener,
        ChooseSalesroomDialog.ChooseSalesroomListener, CostAnalysisContract.View, ChooseDateDialog.ChooseDateListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private CostGrossProfitFragment mHighFragment;
    private CostGrossProfitFragment mLowFragment;
    private CostGrossProfitFragment mCommonFragment;
    private CostGrossProfitFragment mLoseFragment;

    private String[] mDataList = {"高毛利", "低毛利", "一般毛利", "负毛利"};
    private List<Fragment> mFragments;

    private ChooseSalesroomDialog mDialog;
    private String salesRoomIds = "";
    private SalesroomOrWarehouseInfo mInfo;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();

    private ChooseDateDialog chooseDateDialog;
    private Date startDate;
    private Date endDate;
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

    private String strStartDate;
    private String strEndDate;

    private CostAnalysisPresenter mPresenter;
    private int mPosition;

    public CostAnalysisFragment() {
    }

    public static CostAnalysisFragment newInstance(String param1, String param2) {
        CostAnalysisFragment fragment = new CostAnalysisFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mDialog) {
            mDialog.dismiss();
        }

        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }
    }

    @Override
    protected FragmentCostAnalysisBinding getViewBinding() {
        return FragmentCostAnalysisBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initView(View view) {
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroom();
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setChooseSalesroomListener(this);

        initDate();
        initPresenter();
        initFragments();
        initMagicIndicator();

        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDateDialog = new ChooseDateDialog(getContext(), "选择时间", startDate, CostAnalysisFragment.this, "startDate");
            }
        });
    }

    @Override
    protected void loadData() {

    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();
    }

    private void initPresenter() {
        mPresenter = new CostAnalysisPresenter();
        mPresenter.takeView(this);
    }

    private void initFragments() {
        mHighFragment = CostGrossProfitFragment.newInstance(salesRoomIds, strStartDate, strEndDate, 1);
        mLowFragment = CostGrossProfitFragment.newInstance(salesRoomIds, strStartDate, strEndDate, 2);
        mCommonFragment = CostGrossProfitFragment.newInstance(salesRoomIds, strStartDate, strEndDate, 3);
        mLoseFragment = CostGrossProfitFragment.newInstance(salesRoomIds, strStartDate, strEndDate, 4);

        mFragments = new ArrayList<>(4);
        mFragments.add(mHighFragment);
        mFragments.add(mLowFragment);
        mFragments.add(mCommonFragment);
        mFragments.add(mLoseFragment);

        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return mDataList[position];
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }
        };
        viewBinding.viewPager.setAdapter(adapter);

        viewBinding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                Timber.tag("hhh").e("position= " + position);
                mPosition = position;
                setLabel(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void initMagicIndicator() {
        final List<String> titleList = new ArrayList<>(4);
        titleList.add("高毛利");
        titleList.add("低毛利");
        titleList.add("一般毛利");
        titleList.add("负毛利");
        CommonNavigator commonNavigator = new CommonNavigator(this.mActivity);
        MagicIndicatorAdapter magicIndicatorAdapter = new MagicIndicatorAdapter(this.mActivity, viewBinding.viewPager);
        magicIndicatorAdapter.setTitleList(titleList);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(magicIndicatorAdapter);
        viewBinding.magicIndicator.setNavigator(commonNavigator);

        ViewPagerHelper.bind(viewBinding.magicIndicator, viewBinding.viewPager);
    }

    private void setDateText() {
        strStartDate = simpleDateFormat.format(startDate);
        strEndDate = simpleDateFormat.format(endDate);
        String date = textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate);
        viewBinding.tvDate.setText(date);
    }

    private void setLabel(int position) {
        switch (position) {
            case 0:
                loadHighData();
                break;
            case 1:
                loadLowData();
                break;
            case 2:
                loadCommonData();
                break;
            case 3:
                loadLoseData();
                break;
            default:
                break;
        }
    }

    private void loadHighData() {
        if (null != mHighFragment) {
            mHighFragment.loadData(salesRoomIds, strStartDate, strEndDate, 1);
        }
    }

    private void loadLowData() {
        if (null != mLowFragment) {
            mLowFragment.loadData(salesRoomIds, strStartDate, strEndDate, 2);
        }
    }

    private void loadCommonData() {
        if (null != mCommonFragment) {
            mCommonFragment.loadData(salesRoomIds, strStartDate, strEndDate, 3);
        }
    }

    private void loadLoseData() {
        if (null != mLoseFragment) {
            mLoseFragment.loadData(salesRoomIds, strStartDate, strEndDate, 4);
        }
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroom();
        } else {
            mDialog = new ChooseSalesroomDialog(this.mActivity, salesroomInfos, CostAnalysisFragment.this);
        }
    }

    private void getSalesroom() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void getSalesroomInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        Timber.tag("hhh").e("getSalesroomInfoListSuccess resp= " + list.size());

        mDialog = new ChooseSalesroomDialog(this.mActivity, salesroomInfos, CostAnalysisFragment.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure msg= " + msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this.getContext(), "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this.mActivity, "选择结束时间", endDate, this, "endDate");
        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this.getContext(), "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            flushData();
        }
        setDateText();
    }

    private void flushData() {
        strStartDate = dateFormat.format(startDate);
        strEndDate = dateFormat.format(endDate);
        setLabel(mPosition);
    }

    @Override
    public void onChooseSalesroomListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        flushData();
    }

    private String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = salesroomInfos;
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }

        if (infos.size() > 0) {
            mInfo = infos.get(0);
        }
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(infos);
        return ids;
    }
}
